<script setup>
    import adminApi from '@/api/admin/admin.js'
    import {ref, reactive, onMounted} from "vue";
    import { ElMessage ,ElMessageBox} from 'element-plus'
    import {
      Delete,
      Edit,
    } from '@element-plus/icons-vue'
    //import admin from "@/api/admin.js";


    const adminQuery = reactive({
      name:'',
      phone:'',
      page:1,
      limit:10
    })
    const list = ref([])
    const total = ref(0)

        // 使用 onMounted 生命周期钩子获取数据
    /*onMounted(async () => {
      const res = await adminApi.list(adminQuery);
      list.value = res.data.list; // 更新 list
      total.value = res.data.total; // 假设 total 在响应中也有
    });*/
    loadData()
    function loadData(){
      adminApi.list(adminQuery).then(result =>{
        list.value = result.data.list
        total.value = result.data.total
      })
    }
    const onSearch=()=>{
      adminQuery.page = 1
      loadData()
    }

    //delete
    function deleteById(id){
      ElMessageBox.confirm(
          'proxy will permanently delete the data. Continue?',
          'Warning',
          {
            confirmButtonText: 'OK',
            cancelButtonText: 'Cancel',
            type: 'warning',
          }
      )
          .then(() => {
            adminApi.delete(id).then(result =>{
              if (result.code === 0){
                ElMessage({
                  message: 'Congrats, this is a success message.',
                  type: 'success',
                })
              }//if
            })//adminApi
          })
          .catch(() => {
            ElMessage({
              type: 'info',
              message: 'Delete canceled',
            })
          })

      loadData()
    }
    //deleteAll
    const ids = ref([])
    function handSelectionChange(rows){
      ids.value = rows.map(row => row.id)
      console.log(ids.value)
    }
    function deleteAll(){

      ElMessageBox.confirm(
          'proxy will permanently delete the data. Continue?',
          'Warning',
          {
            confirmButtonText: 'OK',
            cancelButtonText: 'Cancel',
            type: 'warning',
          }
      )
          .then(()=>{
            adminApi.deleteAll(ids.value).then(result =>{
              if (result.code === 0){
                ElMessage({
                  message: 'Congrats, this is a success message.',
                  type: 'success',
                })
              }//if
              loadData()
            })
          })

    }

    //add or update
    const dialogFormVisible = ref(false);
    const admin = ref({})
    const title = ref()
    function showAddDialog(){
      dialogFormVisible.value = true
      title.value = 'add'
      admin.value = {}
    }
    function showUpdateDialog(id) {
      dialogFormVisible.value = true
      total.value = 'update'
      admin.value = {}
      adminApi.getById(id).then(result =>{
        admin.value = result.data
      })
    }
    function addOrUpdate(){
      //update
      if (admin.value.id !== null){
        adminApi.update(admin.value).then(result =>{
          if (result.code === 0){
            ElMessage({message:"Congrats, this is a success message",type:"success"})
            dialogFormVisible.value=false
          }//if
          else {
            ElMessage({message:"oops, it didn't work",type:"error"})
          }

          loadData()
        })
      }
      //add
      else {
        adminApi.add(admin.value).then(result =>{
          if (result.code === 0){
            ElMessage({message:"Congrats, this is a success message",type:"success"})
          }//if
          else {
            ElMessage({message:"oops, it didn't work",type:"error"})
          }
          dialogFormVisible.value=false
          loadData()
        })
      }
    }

    //upload
    //function handleAvatarSuccess()是返回值函数,已经调用完后端的/upload了
    import { Plus } from '@element-plus/icons-vue'
    function handleAvatarSuccess(result){
      admin.value.image = result.data
    }
    import {useTokenStore} from "@/store/token.js";
    const tokenStore = useTokenStore()
    const headers = ref({
      //携带token传递到后端
      Authorization: tokenStore.token
    })
    //修改status
    /*function handleSwitchChange(row){
      adminApi.updateStatus(row).then(result=>{
        if (result.code == 0){
          ElMessage.success(result.msg)
        }else {
          ElMessage({message:"更新失败",type:"error"})
        }
      })
    }*/
    //修改status状态
    const handleSwitchChange = (row) => {
      adminApi.updateStatus(row).then(result => {
        if (result.code == 0) {
          ElMessage.success(result.msg)
        } else {
          ElMessage.error(result.msg)
        }
      })
    }
</script>

<template>
  <el-card>
  <template #header>
<!--  两个按钮，添加和批量删除-->
  <el-button type="primary" plain @click="showAddDialog ">添加</el-button>
  <el-button type="primary" plain @click="deleteAll">批量删除</el-button>
  </template>
<!--  搜索-->

  <el-form :inline="true">
    <el-form-item label="名字" >
      <el-input  v-model="adminQuery.name" placeholder="请输入名字" clearable style="width: 180px"/>
    </el-form-item>
    <el-form-item label="手机号" >
      <el-input v-model="adminQuery.phone" placeholder="请输入手机号" clearable style="width: 180px"/>
    </el-form-item>
      <el-form-item label="更新时间" >
        <el-date-picker
            v-model="adminQuery.beginUpdateTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="开始时间"
        />
        <el-date-picker
            v-model="adminQuery.endUpdateTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="结束时间"
        />
    </el-form-item>
    <el-form-item >
      <el-button type="primary" @click="onSearch">搜索</el-button>
    </el-form-item>
  </el-form>
<!--  表格-->
  <el-table :data="list" style="width: 100%" @selection-change="handSelectionChange">
    <el-table-column type="selection" width="55" />
    <el-table-column fixed prop="id" label="ID" width="150"/>
    <el-table-column prop="name" label="名字"/>
<!--    <el-table-column prop="password" label="密码"/>-->
    <el-table-column prop="phone" label="电话"/>
    <el-table-column prop="email" label="邮箱"/>
    <el-table-column prop="image" label="头像">
      <template #default="scope">
        <img :src="scope.row.image" style="max-height: 40px; max-width: 120px;"/>
      </template>
    </el-table-column>
    <el-table-column prop="status" label="状态">
      <template #default="scope">
        <el-tooltip :content="'Switch value: ' + value" placement="top">
          <el-switch
              v-model="scope.row.status"
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
              :active-value="1"
              :inactive-value="0"
              @change="handleSwitchChange(scope.row)"
          />
        </el-tooltip>
      </template>
    </el-table-column>
    <el-table-column prop="updateTime" label="更新时间" width="280"/>
    <el-table-column fixed="right" label="Operations" min-width="80">
      <template #default="{row}">
        <el-button type="danger" :icon="Delete" circle @click="deleteById(row.id)" />
        <el-button type="primary" :icon="Edit" circle @click="showUpdateDialog(row.id)"/>
      </template>
    </el-table-column>
  </el-table>
  <div class="demo-pagination-block" style="margin-top: 20px">

    <el-pagination
        v-model:current-page="adminQuery.page"
        v-model:page-size="adminQuery.limit"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @change="loadData"
    />
  </div>

<!--  add or update-->
    <!--添加、编辑弹出框-->
    <el-dialog v-model="dialogFormVisible" :title="title" width="500" :lock-scroll="false">
      <el-form :model="admin">
        <el-form-item label="名字" :label-width="60">
          <el-input v-model="admin.name" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="密码" :label-width="60">
          <el-input v-model="admin.password" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="60">
          <el-input v-model="admin.email" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="手机号" :label-width="60">
          <el-input v-model="admin.phone" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="头像" :label-width="60">
          <el-upload
              class="avatar-uploader"
              action="/api/admin/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :headers="headers"
          >
            <img v-if="admin.image" :src="admin.image" class="avatar"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="addOrUpdate">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.demo-date-picker {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
}
.demo-date-picker .block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
}
.demo-date-picker .block:last-child {
  border-right: none;
}
.demo-date-picker .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
</style>